package com.ykl.utils;

import com.ykl.common.CommonData;
import com.ykl.method.GenerateRandom;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class LuckDrawUtils {
    double sum = 0;

    /**
     * 取值
     */
    public Object getData(List<CommonData> luckDrawlist, GenerateRandom generateRandom) throws Exception {
        if (luckDrawlist.isEmpty()) {
            throw new IllegalArgumentException("LuckDraw为空!");
        }
        confirm(luckDrawlist);

        /**
         * 取随机数
         */
        double randomNum = getRandom(1000, generateRandom);
        int currentTotal = 0;
        for (CommonData luckDraw : luckDrawlist) {
            currentTotal += luckDraw.getProb() * 1000;
            if (randomNum <= currentTotal) {
                return luckDraw.getData();
            }
        }
        return null;
    }

    private double getRandom(int total, GenerateRandom generateRandom) {
        double randomNum = 0;
        if (generateRandom == null) {
            randomNum = generatorRandomNum(total);
        } else {
            randomNum = generateRandom.getRandom();
        }
        return randomNum;
    }

    /**
     * 从luckDrawlist集合中获取概率集合
     */

    private List<Double> convertToDoubleList(List<CommonData> luckDrawlist) {
        if (luckDrawlist.isEmpty()) {
            throw new IllegalArgumentException("LuckDraw为空!");
        }
        List<Double> probList = new ArrayList<>();
        luckDrawlist.forEach(luckDraw -> probList.add(luckDraw.getProb()));
        return probList;
    }

    /**
     * 判断概率值是否合理
     * 每一个都大于等于0，总和=1
     */
    private void confirm(List<CommonData> luckDrawlist) {
        List<Double> probList = convertToDoubleList(luckDrawlist);
        if (probList.isEmpty()) {
            throw new IllegalArgumentException("概率集合为空!");
        }
        probList.forEach(prob -> {
            if (prob < 0 || prob > 1) {
                throw new IllegalArgumentException("概率值必须是0-1之间的小数");
            }
            String probStr = prob.toString().substring(prob.toString().indexOf(".") + 1);
            if (probStr.length() > 3) {
                String virual = prob.toString().substring(0, prob.toString().indexOf(".") + 3);
                if (prob != Double.parseDouble(virual)) {
                    throw new IllegalArgumentException("概率值只能有三位有效小数数字");
                }
            }
            sum += prob;
        });
        if (sum != 1) {
            throw new IllegalArgumentException("概率值设置不合理，总和需等于1!");
        }
    }

    /**
     * 生成随机数
     */
    private int generatorRandomNum(int total) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return random.nextInt(total) + 1;
    }
}
